<?php
class MY_Controller extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        define("SITEURL",site_url());
        define("BASEURL","http://123.57.228.109:1314/");
		//define("BASEURL",'http://127.0.0.1/');
        define("STATICURL",BASEURL."Public/statics/");
        define("UPLOADURL",BASEURL);
        define("VIEWURL",BASEURL."views/");
        $this->init();
    }
    public function init()
    {
        $currentClass = $this->router->fetch_class(); 
        if(!in_array($currentClass, ['login','news','index'])){
            $login_status  = $this->check_login_status();
            if (empty($login_status)){
                redirect('/login/index');die;
            }
            $emailCnt = $this->getUnreadMegCnt();
            $this->load->vars(['emailCnt'=>$emailCnt]);
        }
    }
    /**
     * 获取当前链接
    */
    public function viewHistroy($data = array()){
        $this->load->model('History_model','history');
        $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
        $php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
        $path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
        $relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.$_SERVER['QUERY_STRING'] : $path_info);
        $viewlink = $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '').$relate_url;
        $data['viewlink'] = $viewlink;
        $this->history->createHistoryRecord($data);
    }
    public function assign($key,$val) {
        $this->cismarty->assign($key,$val);
    }

    public function display($html) {
        $this->cismarty->display($html);
    }
    public function fetch_new($tpl){
        return $this->cismarty->fetch($tpl);
    }

    public function check_login_status()
    {
        $this->load->model('User_model', 'user');
        return $this->user->get_login_status();
    }
    public function getUnreadMegCnt(){
        $this->load->model('Email_model', 'email');
        $emailCnt = $this->email->getMyEmailListCnt(true);
        return $emailCnt;
    }

    function create_page_links($base_url,$total_cnt,$limit,$underlinepage=0)
    {
        $this->load->library('Pagination');
        $conf_page  = array('base_url'=>$base_url,
                'total_rows'=>$total_cnt,
                'per_page'=>$limit,
                'page_query_string'=>true,
                'first_tag_open'=>'<span class="page_btn">',
                'first_tag_close'=>'</span>',
                'last_tag_open'=>'<span  class="page_btn">',
                'last_tag_close'=>'</span>',
                'prev_tag_open'=>'<span  class="page_btn">',
                'prev_tag_close'=>'</span>',
                'next_tag_open'=>'<span  class="page_btn">',
                'next_tag_close'=>'</span>',
                'num_tag_open'=>'<span  class="page_btn">',
                'num_tag_close'=>'</span>',
                'cur_tag_open'=>'<span  class="page_btn current">',
                'cur_tag_close'=>'</span>',
                'first_link'=>'首页',
                'prev_link'=>'上页',
                'next_link'=>'下页',
                'last_link'=>'末页',
                'num_links'=>2,
                'total_lang'=>'共',
                'pages_lang'=>'页',
                'tiao_lang'=>'条');
        //下划线分页
        $this->pagination->initialize($conf_page);
        $page_links = $this->pagination->create_links();
        return $page_links;
    }
    public function fetchSurveyTemp($questionList, $tmpBasePath)
    {
        $questionTemp = "";
        $qIndex = 0;
        if (is_array($questionList)) {
            foreach ($questionList as $qk => $q) {
                $q['qIndex'] = ++$qIndex;
                $qtype = isset($q['questionType']) ? $q['questionType'] : "";
                $tpl = $this->findQuesTpl($qtype, $tmpBasePath);
                $questionTemp .= $tpl ? $this->fetchTemp($tpl, $q) : "";
            }
        }
        return $questionTemp;
    }

    private function findQuesTpl($qtype, $BasePath)
    {
        switch ($qtype) {
            case 1:
                $tpl = $BasePath . "radio.tpl";
                break;
            case 2:
                $tpl = $BasePath . "checkbox.tpl";
                break;
            case 3:
                $tpl = $BasePath . "ifnot.tpl";
                break;
            case 4:
                $tpl = $BasePath . "input.tpl";
                break;
            case 5:
                $tpl = $BasePath . "textarea.tpl";
                break;
        }
        return $tpl;

    }
    private function fetchTemp($tpl,$qData){
        try{
            if(is_array($qData)){
                foreach($qData as $singleKey=>$singleValue){
                    $this->assign($singleKey,$singleValue);
                }
            }
            return $this->fetch_new($tpl);

        }catch(Exception $e){
            //return $e->getMessage();
        }
    }
    protected function response_data($data){

        $this->output->set_header('Content-Type: application/json; charset=utf-8');
        $stander = array("status"=>array("code"=>200,"msg"=>"ok"),"data"=>$data);
        return json_encode($stander);
    }

    
}


class BaseController extends MY_Controller
{
    public function __construct()
    {
        parent::__construct();
        
        $this->init(); 
    }
    /**
     * 登陆状态检测
     */
    
    public function userInfo($token){
        $this->load->model("user_model","user");
        $userInfo = $this->user->getUserInfoByToken($token);
        if($userInfo['AccountID']){
            $this->user->edit_user($userInfo['AccountID'],array("last_use_time"=>time()));    
        }
        return $userInfo;
    }


}

   

//后台管理控制器
class MY_Luckydog extends CI_Controller
{
	public function __construct()
	{
		parent::__construct();
        $this->load->library('encrypt');
        define("BASEURL","http://123.57.228.109:1314/");
        //define("BASEURL","http://127.0.0.1/");
        define("STATICURL",BASEURL."Public/luckydogstatics/");
        define("UPLOADURL",BASEURL.'uploads');
        $this->init();

	}

    public function init()
    {
        $currentClass = $this->router->fetch_class(); 
        if($currentClass != "login"){
            $login_status  = $this->check_login_status();
            if (empty($login_status)){
                redirect('/luckydog/login');die;
            }
        }
    }


	/**
	 * 登陆状态检测
	 */
	public function check_login_status()
	{
		$this->load->model('luckydog/admin_user_model', 'admin_user');
		return $this->admin_user->get_login_status();
	}



    function create_page_links($base_url,$total_cnt,$limit)
    {
        $this->load->library('Pagination');
        $conf_page	= array('base_url'=>$base_url,
            'total_rows'=>$total_cnt,
            'per_page'=>$limit,
            'page_query_string'=>true,
            'first_tag_open'=>'<span class="page_btn">',
            'first_tag_close'=>'</span>',
            'last_tag_open'=>'<span  class="page_btn">',
            'last_tag_close'=>'</span>',
            'prev_tag_open'=>'<span  class="page_btn">',
            'prev_tag_close'=>'</span>',
            'next_tag_open'=>'<span  class="page_btn">',
            'next_tag_close'=>'</span>',
            'num_tag_open'=>'<span  class="page_btn">',
            'num_tag_close'=>'</span>',
            'cur_tag_open'=>'<span  class="page_btn current">',
            'cur_tag_close'=>'</span>',
            'first_link'=>'首页',
            'prev_link'=>'上页',
            'next_link'=>'下页',
            'last_link'=>'末页',
            'num_links'=>5,
            'total_lang'=>'共',
            'pages_lang'=>'页',
            'tiao_lang'=>'条');
        $this->pagination->initialize($conf_page);
        $page_links	= $this->pagination->create_links();
        return $page_links;
    }

        /**
     * 执行群发
     * @author KevinBai
     * @param $type 0：发送  1：存草稿
     * @param $res 1：发送成功  2：存草稿成功
     */
     public function send_email($data =[])
     {
        $this->load->model('luckydog/Emailsender_model', 'emailsender');
        $type = isset($data['type']) ? $data['type'] : 0;
        $draftid = isset($data['draftid']) ? $data['draftid'] : 0;
        $departmentid = isset($data['departmentid']) ? $data['departmentid'] :0; 
        $usernames =  isset($data['usernames']) ? $data['usernames'] : '';  
        $tosendtype = isset($data['tosendtype']) ? $data['tosendtype'] : '';  

        $subject = isset($data['subject']) ? $data['subject'] : ''; 
        $content =  isset($data['content']) ? $data['content'] : '';  
        $messageType = isset($data['messageType']) ? $data['messageType'] :''; 

        $data_fd['tosendtype'] = $tosendtype;
        $data_fd['from_userid'] = $_SESSION['adminUserInfo']['id'];    
        
        $data_fd['subject'] = $subject;
        $data_fd['content'] = $content;
        $data_fd['messageType'] = $messageType;
        $data_fd['addtime'] = time();

        //针对来自草稿箱的数据处理
        if(!empty($draftid))
        {
            //存稿
            if(!empty($type) && !empty($draftid))
            {
                $data_fd['draft_status'] = 1;
                $res = $this->emailsender->update_data($draftid,$data_fd);
                $res = $this->pushMessage($draftid,$tosendtype,$departmentid,$usernames);
                if($res)
                {
                    $res = 2;
                }
            }
            //发送
            if(empty($type) && !empty($draftid))
            {
                $data_fd['draft_status'] = 0;
                $res = $this->emailsender->update_data($draftid,$data_fd);

                //执行消息推送
                $res = $this->pushMessage($draftid,$tosendtype,$departmentid,$usernames);
            }
        }
        else
        {
            //直接发送处理
            $data_fd['draft_status'] = $type;
            $draftid = $this->emailsender->insert_data($data_fd);

            //推送消息
            $res = $this->pushMessage($draftid,$tosendtype,$departmentid,$usernames);
        }
        return $res;
     }

     public function pushMessage($draftid,$tosendtype = '',$departmentid = '',$usernames = ''){
        $data_push['type'] = 0;
        $data_push['typeid'] = $draftid;
        $data_push['from_userid'] = $_SESSION['adminUserInfo']['id'];
        $data_push['from_username'] = $_SESSION['adminUserInfo']['username'];
        $data_push['createtime'] = time();

        $userid_arr = [];
        $this->load->model('luckydog/User_model', 'user');
        $data['fields'] = 'AccountID';
        $data['tosendtype'] = $tosendtype;
        if($departmentid){
            $data['departmentid'] = $departmentid;
        }
        if($usernames){
            ;
            $data['usernames'] = "'".str_replace(",", "','", $usernames)."'";
        }
        $offset = 0;
        while($userList =$this->user->userList($data,$offset,20)){
            $insertData_arr = [];
            $offset += count($userList);
            foreach($userList as $user){
                $insertData_arr[] = "(".$data_push['type'].",".$data_push['typeid'].",".$user['AccountID'].",".$data_push['from_userid'].",".$data_push['createtime'].",'".$data_push['from_username']."')";
            }
            $insertData_str = !empty($insertData_arr)?implode(",", $insertData_arr):'';
            if($insertData_str){
                $res = $this->emailsender->do_push($insertData_str);    
            }
            if(!$userList || count($userList) <=20) break;
        }
        return $res?1:0;
     }


}

?>
